/**
 * Created by houjianhui on 2017/7/19.
 */
'use strict';
wmsCtrl.controller('stockUnitCtrl', ['$scope', 'stockUnitService', 'dropDownService', function (scope, stockUnitService, dropDownService) {   //库位查询

    //更多条件
    scope.moreText = scope.constant.moreText.spread;
    scope.moreClick = function () {
        scope.otherForm = !scope.otherForm;
        if (scope.otherForm) {
            scope.moreText = scope.constant.moreText.packUp;
        } else {
            scope.moreText = scope.constant.moreText.spread;
        }
    }

    /*状态数据*/
    scope.dropDownList = {
        status: scope.Tools.dropDown.stockUnitStatusDropDown.concat()    //库位状态
    }
    scope.dropDownList.status.unshift(scope.constant.defaultDropDownNullData) //插入状态空数据

    //设置默认值
    scope.dropDownDefault = {
        status: scope.dropDownList.status[0] //库位状态
    }

    //库区查询
    scope.dropDownService.getZoneList(scope.userInfo.whCode)
        .then(function (result) {
            if (result.success) {
                scope.dropDownList.zone = result.data;
                scope.dropDownList.zone.unshift(scope.constant.defaultDropDownNullData);
                scope.dropDownDefault.zone = scope.dropDownList.zone[0];
            } else {
                scope.Tools.alert(result.message);
            }
        })

    //新增库位 click
    scope.addStockUnitClick = function () {
        scope.dropDownService.getZoneList(scope.userInfo.whCode)
            .then(function (result) {
                if (result.success) {
                    scope.Tools.dialog({
                        controller: 'stockUnitCtrl.dialog',
                        template: 'templates/locationManagement/stockUnitManagement/stock-unit-form.html',
                        closeByDocument: false,
                        closeByEscape: false,
                        data: {
                            zone: result.data,
                            locType: scope.Tools.dropDown.locTypeStatusDropDown,   //库位类型
                            locSize: scope.Tools.dropDown.locSizeStatusDropDown,   //库位存车类型
                            dropDownDefault: {    //下拉框默认值
                                zone: result.data[0],
                                locType: scope.Tools.dropDown.locTypeStatusDropDown[0],
                                locSize: scope.Tools.dropDown.locSizeStatusDropDown[0]
                            },
                            stockUnit: {
                                locWhName: scope.userInfo.whName,
                                locWhCode: scope.userInfo.whCode
                            }
                        },
                        width: 530,
                        title: '新增库位',
                        scope: scope
                    })
                } else {
                    scope.Tools.alert(result.message);
                }
            })
    }

    //更新库位 click
    scope.modifyStockUnitClick = function () {

        var indexArr = scope.Tools.getTableSelectItemIndex('.stockUnitTable');  //获取table所选的下标

        if (indexArr.length == 0) {
            scope.Tools.alert('请选择需要更新的数据');
            return;
        }

        if (indexArr.length > 1) {
            scope.Tools.alert('只能选择一条数据进行更新');
            return;
        }
        //查询库位数据
        stockUnitService.getById(scope.stockUnitList[indexArr[0]].locId)
            .then(function (result) {
                if (result.success) {
                    var warehouse = {
                        whName: result.data.locWhName,
                        whCode: result.data.locWhCode
                    }
                    var defaultLocType = null;  //库位类型
                    var defaultLocSize = null;  //库位存车类型
                    for (var i = 0; i < scope.Tools.dropDown.locTypeStatusDropDown.length; i++) {
                        if (result.data.locType == scope.Tools.dropDown.locTypeStatusDropDown[i].value) {
                            defaultLocType = scope.Tools.dropDown.locTypeStatusDropDown[i]
                        }
                    }

                    for (var i = 0; i < scope.Tools.dropDown.locSizeStatusDropDown.length; i++) {
                        if (result.data.locSize == scope.Tools.dropDown.locSizeStatusDropDown[i].value) {
                            defaultLocSize = scope.Tools.dropDown.locSizeStatusDropDown[i]
                        }
                    }

                    //获取库区信息
                    scope.dropDownService.getZoneList(warehouse.whCode)
                        .then(function (zoneResult) {
                            if (zoneResult.success) {
                                //库区默认值
                                var defaultZone = null;
                                for (var i = 0; i < zoneResult.data.length; i++) {
                                    if (zoneResult.data[i].zeZoneCode == result.data.locZoneCode) {
                                        defaultZone = zoneResult.data[i];
                                    }
                                }

                                scope.Tools.dialog({
                                    controller: 'stockUnitCtrl.dialog',
                                    template: 'templates/locationManagement/stockUnitManagement/stock-unit-form.html',
                                    closeByDocument: false,
                                    closeByEscape: false,
                                    data: {
                                        zone: zoneResult.data,
                                        locType: scope.Tools.dropDown.locTypeStatusDropDown,   //库位类型
                                        locSize: scope.Tools.dropDown.locSizeStatusDropDown,   //库位存车类型
                                        dropDownDefault: {    //下拉框默认值
                                            warehouse: warehouse, //仓库默认值
                                            zone: defaultZone,   //库区默认值
                                            locType: defaultLocType,   //库位类型
                                            locSize: defaultLocSize    //库位存车类型
                                        },
                                        stockUnit: result.data
                                    },
                                    width: 530,
                                    title: '更新库位',
                                    scope: scope
                                })
                            } else {
                                scope.Tools.alert(zoneResult.message);
                            }
                        })
                } else {
                    scope.Tools.alert(result.message);
                }
            })
    }

    //批量新增库位 click
    scope.addBatchStockUnitClick = function () {
        scope.Tools.dialog({
            controller: 'stockUnitCtrl.dialog',
            template: 'templates/locationManagement/stockUnitManagement/stock-unit-batch-add.html',
            closeByDocument: false,
            closeByEscape: false,
            width: 530,
            title: '批量新增库位',
            scope: scope
        })
    }

    //列表条件参数
    scope.listParam = function () {

        if (!scope.search) {
            scope.search = {};
        }

        scope.search.pageSize = scope.pageSize;    //设置最大页
        if (!scope.fristSelect) { //不是第一次查询 则设置当前页
            scope.search.pageNo = scope.pageNo;
        } else {  //第一次查询设置为　第一页
            scope.search.pageNo = scope.constant.pageNo;
        }

        if (scope.otherForm) {    //展开了更多
            scope.search.locEnableFlag = scope.dropDownDefault.status.value;   //状态
            scope.search.locWhCode = scope.userInfo.whCode;     //仓库code
            scope.search.locZoneId = scope.dropDownDefault.zone.zeId;   //库区id
            scope.search.locZoneCode = scope.dropDownDefault.zone.zeZoneCode;   //库区code
            return scope.search;
        } else {
            return scope.search;
        }
    }

    //列表
    scope.fristSelect = true;   //判断是否是第一次查询
    scope.list = function (params) {
        //设置分页参数
        if (!params) {
            params = {};
        }
        params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
        params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo;

        stockUnitService.list(params)
            .then(function (result) {
                if (result.success) {
                    scope.stockUnitList = result.data.wmsLocationList;
                    if (scope.fristSelect) {
                        scope.Tools.page(document.getElementById('pages'), {
                            pages: result.data.wmsLocationBO.totalPage,
                            curr: result.data.wmsLocationBO.pageNo,
                            count: result.data.wmsLocationBO.totalRecord
                        }, function (obj, first) {
                            scope.fristSelect = first;  //设置状态
                            //初始化多选框
                            scope.Tools.initCheckBox();
                            if (!first) { //判断不是第一次加载
                                var param = scope.listParam();
                                param.pageNo = obj.curr;    //当前页
                                param.pageSize = obj.limit; //最大页
                                scope.pageSize = obj.limit; //设置最大页
                                scope.pageNo = obj.curr; //设置当前页
                                scope.list(param);
                            }
                        })
                    } else {
                        //初始化多选框
                        scope.Tools.initCheckBox();
                    }

                } else {
                    scope.Tools.alert(result.message);
                }
            })
    }

    //列表
    scope.list();

    //查询 click
    scope.searchClick = function () {
        scope.fristSelect = true;   //设置为第一次查询
        scope.list(scope.listParam());
    }

    //重置 click
    scope.resetClick = function () {
        scope.search = {};
        scope.dropDownDefault.warehouse = scope.dropDownList.warehouse[0];
        scope.dropDownDefault.zone = scope.dropDownList.zone[0];
        scope.dropDownDefault.status = scope.dropDownList.status[0];
    }

    //刷新 click
    scope.refreshClick = function () {
        scope.searchClick();
    }

    //启用 click
    scope.startStockUnitClick = function () {
        var indexArr = scope.Tools.getTableSelectItemIndex('.stockUnitTable');  //获取table所选的下标

        if (indexArr.length == 0) {
            scope.Tools.alert('请选择需要启用的数据');
            return;
        }

        //选中的库位数据
        var stockUnitList = scope.Tools.getDataTOIndex(indexArr, scope.stockUnitList);

        scope.Tools.dialogConfirm('确定要启用选中的数据吗？')
            .then(function (res) {
                if (res) {
                    stockUnitService.enableLocation(stockUnitList, scope.constant.stockUnitStatus.start)
                        .then(function (result) {
                            if (result.success) {
                                scope.Tools.alert('启用数据成功');
                                scope.list(scope.listParam());
                            } else {
                                scope.Tools.alert(result.message);
                            }
                        })
                }
            })
    }

    //禁用 click
    scope.stopStockUnitClick = function () {
        var indexArr = scope.Tools.getTableSelectItemIndex('.stockUnitTable');  //获取table所选的下标

        if (indexArr.length == 0) {
            scope.Tools.alert('请选择需要启用的数据');
            return;
        }

        //选中的库位数据
        var stockUnitList = scope.Tools.getDataTOIndex(indexArr, scope.stockUnitList);

        scope.Tools.dialogConfirm('确定要禁用选中的数据吗？')
            .then(function (res) {
                if (res) {
                    stockUnitService.enableLocation(stockUnitList, scope.constant.stockUnitStatus.stop)
                        .then(function (result) {
                            if (result.success) {
                                scope.Tools.alert('禁用数据成功');
                                scope.list(scope.listParam());
                            } else {
                                scope.Tools.alert(result.message);
                            }
                        })
                }
            })
    }
}])
    .controller('stockUnitCtrl.dialog', ['$scope', 'stockUnitService', 'dropDownService', function (scope, stockUnitService, dropDownService) {   //库位dialog

        //新增或更新
        scope.addOrUpdateClick = function () {

            if (!scope.ngDialogData.stockUnit) {
                scope.ngDialogData.stockUnit = {};
            }
            console.log('a', scope.ngDialogData.dropDownDefault.locType)
            console.log('b', scope.ngDialogData.dropDownDefault.locSize)
            scope.ngDialogData.stockUnit.locType = scope.ngDialogData.dropDownDefault.locType ? scope.ngDialogData.dropDownDefault.locType.value : '';    //库位类型
            scope.ngDialogData.stockUnit.locSize = scope.ngDialogData.dropDownDefault.locSize ? scope.ngDialogData.dropDownDefault.locSize.value : '';    //库位存车类型

            //有库位id则为更新 没有则为 新增
            if (scope.ngDialogData.stockUnit.locId) {
                stockUnitService.update(scope.ngDialogData.stockUnit)
                    .then(function (result) {
                        if (result.success) {
                            scope.Tools.alert('更新库位成功');
                            scope.$parent.fristSelect = true;   //设置为第一次查询
                            scope.list();
                            scope.closeThisDialog();
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })

            } else {
                stockUnitService.add(scope.ngDialogData.stockUnit)
                    .then(function (result) {
                        if (result.success) {
                            scope.Tools.alert('新增库位成功');
                            scope.$parent.fristSelect = true;   //设置为第一次查询
                            scope.list();
                            scope.closeThisDialog();
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })
            }
        }

        //库区修改 change
        scope.changeZoneChange = function (item) {
            if (!scope.ngDialogData.stockUnit) {
                scope.ngDialogData.stockUnit = {};
            }
            if (item) {
                scope.ngDialogData.stockUnit.locZoneCode = item.zeZoneCode;
                scope.ngDialogData.stockUnit.locZoneName = item.zeZoneName;
                scope.ngDialogData.stockUnit.locZoneId = item.zeId;
            }
        }
        scope.changeZoneChange(scope.ngDialogData.dropDownDefault.zone);
    }])
    .controller('stockUnitStrategyCtrl', ['$scope', 'stockUnitStrategyService', 'dropDownService', function (scope, stockUnitStrategyService, dropDownService) {  //库位策略 controller
        //列表条件参数
        scope.listParam = function () {

            if (!scope.search) {
                scope.search = {};
            }

            if (!scope.fristSelect) { //不是第一次查询 则设置当前页
                scope.search.pageNo = scope.pageNo;
            } else {  //第一次查询设置为　第一页
                scope.search.pageNo = scope.constant.pageNo;
            }

            if (scope.otherForm) {    //展开了更多
                return scope.search;
            } else {
                return scope.search;
            }
        }

        //列表
        /*scope.fristSelect = true;   //判断是否是第一次查询*/
        scope.list = function (params) {
            //设置分页参数
            if (!params) {
                params = {};
            }
            params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
            params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo

            stockUnitStrategyService.list(scope.userInfo.whCode)
                .then(function (result) {
                    if (result.success) {
                        scope.stockUnitStrategyList = result.data;
                        scope.Tools.initCheckBox();
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //列表
        scope.list();

        //查询 click
        scope.searchClick = function () {
            scope.fristSelect = true;   //设置为第一次查询
            scope.list(scope.listParam());
        }

        //刷新 click
        scope.refreshClick = function () {
            scope.searchClick();
        }

        //回车按下查询
        scope.searchListKeyDown = function (e) {
            var keycode = window.event ? e.keyCode : e.which;
            if (keycode == 13) {  //回车键
                /*scope.fristSelect = true;   //设置为第一次查询*/
                scope.list(scope.listParam());
                e.preventDefault();
            }
        }

        //新增策略 click
        scope.addStockUnitStrategyClick = function () {
            //查询仓库
            dropDownService.getWarehouse()
                .then(function (result) {
                    if (result.success) {
                        scope.Tools.dialog({
                            controller: 'stockUnitStrategyCtrl.dialog',
                            template: 'templates/strategyManagement/stockUnitStrategy/stock-unit-strategy-form.html',
                            closeByDocument: false,
                            closeByEscape: false,
                            data: {
                                dropDownDefault: { //下拉默认值
                                    warehouse: result.data[0]
                                },
                                warehouse: result.data //仓库
                            },
                            width: 400,
                            title: '新增策略',
                            scope: scope
                        })
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //更新策略 click
        scope.updateStockUnitStrategyClick = function () {
            var indexArr = scope.Tools.getTableSelectItemIndex('.stockUnitStrategyTable');  //获取table所选的下标

            if (indexArr.length == 0) {
                scope.Tools.alert('请选择需要更新的数据');
                return;
            }

            if (indexArr.length > 1) {
                scope.Tools.alert('只能选择一条数据进行更新');
                return;
            }

            //查询仓库
            dropDownService.getWarehouse()
                .then(function (result) {
                    if (result.success) {
                        var newData = angular.copy(scope.stockUnitStrategyList[indexArr[0]]);   //新的数据
                        var defaultWarehouse = null;    //仓库默认值
                        //赋值仓库下拉默认值
                        for (var i = 0; i < result.data.length; i++) {
                            if (newData.pyWhCode == result.data[i].whCode) {
                                defaultWarehouse = result.data[i];
                                break;
                            }
                        }

                        scope.Tools.dialog({
                            controller: 'stockUnitStrategyCtrl.dialog',
                            template: 'templates/strategyManagement/stockUnitStrategy/stock-unit-strategy-form.html',
                            closeByDocument: false,
                            closeByEscape: false,
                            data: {
                                stockUnitStrategy: newData,   //编辑的数据
                                dropDownDefault: { //下拉默认值
                                    warehouse: defaultWarehouse
                                },
                                warehouse: result.data //仓库
                            },
                            width: 400,
                            title: '更新策略',
                            scope: scope
                        })
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })

        }

        //删除 策略 click
        scope.deleteStockUnitStrategyClick = function () {
            var indexArr = scope.Tools.getTableSelectItemIndex('.stockUnitStrategyTable');  //获取table所选的下标

            var stockUnitStrategyList = scope.Tools.getDataTOIndex(indexArr, scope.stockUnitStrategyList);

            if (stockUnitStrategyList.length == 0) {
                scope.Tools.alert('请选择需要删除的数据');
                return;
            }

            scope.Tools.dialogConfirm('确定要删除选中的数据吗？')
                .then(function (res) {
                    if (res) {
                        stockUnitStrategyService.deletePloy(stockUnitStrategyList)
                            .then(function (result) {
                                if (result.success) {
                                    scope.list(scope.listParam());
                                } else {
                                    scope.Tools.alert(result.message);
                                }
                            })
                    }
                })
        }

        //新增策略条件 click
        scope.addConditionClick = function () {
            if (!scope.selectPyCode) {
                scope.Tools.alert('请选择一条策略');
                return;
            }
            //货主信息获取
            dropDownService.getCustomerInfo()
                .then(function (result) {
                    scope.Tools.dialog({
                        controller: 'stockUnitStrategyCtrl.dialog',
                        template: 'templates/strategyManagement/stockUnitStrategy/strategy-condition-form.html',
                        closeByDocument: false,
                        closeByEscape: false,
                        data: {
                            conditionTypeDropDown: scope.Tools.dropDown.strategyConditionTypeDropDown, //条件类型下拉
                            strategyOperatorDropDown: scope.Tools.dropDown.strategyOperatorDropDown,   //条件运算符
                            conditionValueDropDown: result.data,    //货主条件值
                            dropDownDefault: {
                                conditionType: scope.Tools.dropDown.strategyConditionTypeDropDown[0],  //条件类型
                                operator: scope.Tools.dropDown.strategyOperatorDropDown[0], //条件运算符
                                conditionValue: result.data ? result.data[0] : {} //货主条件值
                            }
                        },
                        width: 400,
                        title: '新增策略条件',
                        scope: scope
                    })
                })
        }

        //删除条件 click
        scope.deleteConditionClick = function () {
            var indexArr = scope.Tools.getTableSelectItemIndex('.strategyConditionTable');  //获取table所选的下标

            var conditionList = scope.Tools.getDataTOIndex(indexArr, scope.strategyConditionList);

            if (conditionList.length == 0) {
                scope.Tools.alert('请选择需要删除的数据');
                return;
            }

            scope.Tools.dialogConfirm('确定要删除选中的数据吗？')
                .then(function (res) {
                    if (res) {
                        stockUnitStrategyService.deletePloyCondition(conditionList)
                            .then(function (result) {
                                if (result.success) {
                                    scope.ployConditionList(scope.selectPyCode);
                                } else {
                                    scope.Tools.alert(result.message);
                                }
                            })
                    }
                })
        }

        //新增流向 click
        scope.addFlowtoClick = function () {
            if (!scope.selectPyCode) {
                scope.Tools.alert('请选择一条策略');
                return;
            }
            //获取区域信息
            dropDownService.getArea(0)
                .then(function (result) {
                    if (result.success) {
                        scope.Tools.dialog({
                            controller: 'stockUnitStrategyCtrl.dialog',
                            template: 'templates/strategyManagement/stockUnitStrategy/strategy-flowto-form.html',
                            closeByDocument: false,
                            closeByEscape: false,
                            data: {
                                originAreaList: result.data,   //起始区域
                                destAreaList: result.data //目的区域
                            },
                            width: 800,
                            title: '新增流向维护',
                            scope: scope
                        })
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //删除流向 click
        scope.deleteFlowtoClick = function () {
            var indexArr = scope.Tools.getTableSelectItemIndex('.strategyFlowtoTable');  //获取table所选的下标

            var flowtoList = scope.Tools.getDataTOIndex(indexArr, scope.strategyFlowtoList);

            if (flowtoList.length == 0) {
                scope.Tools.alert('请选择需要删除的数据');
                return;
            }

            scope.Tools.dialogConfirm('确定要删除选中的数据吗？')
                .then(function (res) {
                    if (res) {
                        stockUnitStrategyService.deletePloyFlowto(flowtoList)
                            .then(function (result) {
                                if (result.success) {
                                    scope.ployFlowtoList(scope.selectPyCode);
                                } else {
                                    scope.Tools.alert(result.message);
                                }
                            })
                    }
                })
        }

        //新增库位策略 click
        scope.addLocationClick = function () {
            if (!scope.selectPyCode) {
                scope.Tools.alert('请选择一条策略');
                return;
            }
            //默认写死仓库code 001
            dropDownService.getZoneList(scope.userInfo.whCode)
                .then(function (result) {
                    if (result.success) {
                        scope.Tools.dialog({
                            controller: 'stockUnitStrategyCtrl.dialog',
                            template: 'templates/strategyManagement/stockUnitStrategy/strategy-location-form.html',
                            closeByDocument: false,
                            closeByEscape: false,
                            data: {
                                reservoirDropList: result.data,    //库区下拉
                                dropDownDefault: {
                                    reservoir: result.data[0]  //库区默认值
                                }
                            },
                            width: 550,
                            title: '新增库位策略',
                            scope: scope
                        })
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //删除库位 click
        scope.deleteLocationClick = function () {
            var indexArr = scope.Tools.getTableSelectItemIndex('.strategyLocationTable');  //获取table所选的下标

            var conditionList = scope.Tools.getDataTOIndex(indexArr, scope.strategyLocationList);

            if (conditionList.length == 0) {
                scope.Tools.alert('请选择需要删除的数据');
                return;
            }

            scope.Tools.dialogConfirm('确定要删除选中的数据吗？')
                .then(function (res) {
                    if (res) {
                        stockUnitStrategyService.deletePloyLocation(conditionList)
                            .then(function (result) {
                                if (result.success) {
                                    scope.ployLocationList(scope.selectPyCode);
                                } else {
                                    scope.Tools.alert(result.message);
                                }
                            })
                    }
                })
        }

        //生成规则
        scope.generateRuleClick = function () {
            stockUnitStrategyService.genPloyContent(scope.selectPyCode)
                .then(function (result) {
                    if (result.success) {
                        scope.ruleContent = result.data;
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //库位策略 条件列表
        scope.ployConditionList = function (pyCode) {
            stockUnitStrategyService.getPloyConditionList(pyCode)
                .then(function (result) {
                    if (result.success) {
                        scope.strategyConditionList = result.data;
                        scope.Tools.initCheckBox();
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //库位策略 流向设置 列表
        scope.ployFlowtoList = function (pyCode) {
            stockUnitStrategyService.getPloyFlowtoList(pyCode)
                .then(function (result) {
                    if (result.success) {
                        scope.strategyFlowtoList = result.data;
                        scope.Tools.initCheckBox();
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //库位策略 库位分配设置 列表
        scope.ployLocationList = function (pyCode) {
            stockUnitStrategyService.getPloyLocationList(pyCode)
                .then(function (result) {
                    if (result.success) {
                        scope.strategyLocationList = result.data;
                        scope.Tools.initCheckBox();
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //选择一行策略 click
        scope.selectItemClick = function (item, e) {
            //设置选择的 策略code
            scope.selectPyCode = item.pyCode;
            //库位策略 条件列表
            scope.ployConditionList(scope.selectPyCode);
            //库位策略 流向设置
            scope.ployFlowtoList(scope.selectPyCode);
            //库位策略 库位分配设置
            scope.ployLocationList(scope.selectPyCode);
            scope.Tools.initTableClick(e);
        }
    }])
    .controller('stockUnitStrategyCtrl.dialog', ['$scope', 'stockUnitStrategyService', 'dropDownService', '$timeout', function (scope, stockUnitStrategyService, dropDownService, timeout) {   //库位策略 dialog
        //新增和更新策略
        scope.saveOrUpdateStrateyClick = function () {
            //赋值仓库的数据
            scope.ngDialogData.stockUnitStrategy.pyWhCode = scope.ngDialogData.dropDownDefault.warehouse.whCode;
            scope.ngDialogData.stockUnitStrategy.pyWhName = scope.ngDialogData.dropDownDefault.warehouse.whName;

            //判断是否有id
            if (scope.ngDialogData.stockUnitStrategy.pyId) {  //更新
                stockUnitStrategyService.updatePloy(scope.ngDialogData.stockUnitStrategy)
                    .then(function (result) {
                        if (result.success) {
                            //刷新列表
                            scope.list(scope.listParam());
                            scope.closeThisDialog();
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })
            } else {  //更新
                stockUnitStrategyService.addPloy(scope.ngDialogData.stockUnitStrategy)
                    .then(function (result) {
                        if (result.success) {
                            //刷新列表
                            scope.list(scope.listParam());
                            scope.closeThisDialog();
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })
            }
        }

        //新增条件click
        scope.saveConditionClick = function () {

            var param = {};
            param.pycPyCode = scope.selectPyCode;   //选择的策略code
            param.pycType = scope.ngDialogData.dropDownDefault.conditionType.value;   //条件类型
            param.pycOperatorCode = scope.ngDialogData.dropDownDefault.operator.value;  //条件运算符
            //货主
            if (scope.ngDialogData.dropDownDefault.conditionType.value == scope.constant.strategyConditionType.shipper) {
                if (scope.ngDialogData.dropDownDefault.conditionValue.customerId) {
                    param.pycValue = scope.ngDialogData.dropDownDefault.conditionValue.customerId.code;
                    param.pycName = scope.ngDialogData.dropDownDefault.conditionValue.customerId.name;
                }
            } else {  //车型
                param.pycValue = scope.ngDialogData.dropDownDefault.conditionValue.code;
                param.pycName = scope.ngDialogData.dropDownDefault.conditionValue.name;
            }
            stockUnitStrategyService.addPloyCondition(new Array(param))
                .then(function (result) {
                    if (result.success) {
                        //刷新列表
                        scope.ployConditionList(scope.selectPyCode);
                        scope.closeThisDialog();
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //条件
        scope.pycTypeDropChang = function (item) {
            if (item.value == scope.constant.strategyConditionType.shipper) { //货主
                dropDownService.getCustomerInfo()
                    .then(function (result) {
                        scope.ngDialogData.conditionValueDropDown = result.data;    //条件值
                        scope.ngDialogData.dropDownDefault.conditionValue = result.data[0];//条件值
                    })
            } else {  //车型
                dropDownService.getVehicleSpec()
                    .then(function (result) {
                        scope.ngDialogData.dropDownDefault.conditionValue = result.data[0]; //条件值
                        scope.ngDialogData.conditionValueDropDown = result.data;    //条件值
                    })
            }
        }

        //保存库位分配
        scope.saveLocalClick = function () {
            scope.ngDialogData.localStrategy.pylZoneName = scope.ngDialogData.dropDownDefault.reservoir.zeZoneName; //库区名称
            scope.ngDialogData.localStrategy.pylZoneCode = scope.ngDialogData.dropDownDefault.reservoir.zeZoneCode; //库区code
            scope.ngDialogData.localStrategy.pylPyCode = scope.selectPyCode;   //选择的策略code
            //新增库位设置
            stockUnitStrategyService.addPloyLocation(new Array(scope.ngDialogData.localStrategy))
                .then(function (result) {
                    if (result.success) {
                        //刷新列表
                        scope.ployLocationList(scope.selectPyCode);
                        scope.closeThisDialog();
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //判断是否传递 tree的数据
        if (scope.ngDialogData.originAreaList && scope.ngDialogData.destAreaList) {   //加载树
            scope.selectOriginClick = function (event, treeId, treeNode) {
                if (!treeNode.children || treeNode.children.length == 0) {
                    dropDownService.getArea(treeNode.id)
                        .then(function (result) {
                            if (result.success) {
                                if (result.data && result.data.length != 0) {
                                    scope.originAreaZree.removeChildNodes(treeNode);
                                    scope.originAreaZree.addNodes(treeNode, result.data);
                                }
                            } else {
                                scope.Tools.alert(result.message);
                            }
                        })
                }
            }

            scope.selectDestClick = function (event, treeId, treeNode) {
                if (!treeNode.children || treeNode.children.length == 0) {
                    dropDownService.getArea(treeNode.id)
                        .then(function (result) {
                            if (result.success) {
                                if (result.data && result.data.length != 0) {
                                    scope.destAreaZree.removeChildNodes(treeNode);
                                    scope.destAreaZree.addNodes(treeNode, result.data);
                                }
                            } else {
                                scope.Tools.alert(result.message);
                            }
                        })
                }
            }

            timeout(function () {
                //起始地
                scope.originAreaZree = $.fn.zTree.init(
                    $('.originTree'),
                    {
                        treeId: 'originTree',
                        data: {
                            key: {
                                name: 'name'
                            },
                            simpleData: {
                                enable: false,
                                idKey: "id",
                                pIdKey: "parentId",
                                rootPId: 0
                            }
                        },
                        check: {
                            enable: true,
                            chkStyle: "checkbox"
                        },
                        view: {
                            showLine: false,
                            showIcon: false,
                            showTitle: false,
                            selectedMulti: false  //设置不能多选
                        },
                        callback: {
                            onClick: scope.selectOriginClick
                        }
                    },
                    scope.ngDialogData.originAreaList
                );
                //目的地
                scope.destAreaZree = $.fn.zTree.init(
                    $('.destTree'),
                    {
                        treeId: 'destTree',
                        data: {
                            key: {
                                name: 'name'
                            },
                            simpleData: {
                                enable: false,
                                idKey: "id",
                                pIdKey: "parentId",
                                rootPId: 0
                            }
                        },
                        check: {
                            enable: true,
                            chkStyle: "checkbox"
                        },
                        view: {
                            showLine: false,
                            showIcon: false,
                            showTitle: false,
                            selectedMulti: false  //设置不能多选
                        },
                        callback: {
                            onClick: scope.selectDestClick
                        }
                    },
                    scope.ngDialogData.destAreaList
                );
            }, 200)

            //获取选中的树节点移动到右边
            scope.rightClick = function () {
                var originTreeNodes = scope.originAreaZree.getCheckedNodes();   //起始地
                var destTreeNodes = scope.destAreaZree.getCheckedNodes();   //目的地

                if (originTreeNodes.length > 0 && destTreeNodes.length > 0) { //判断是否选择了数据
                    var treeList = new Array(); //用来存储过滤后的数据
                    for (var i = 0; i < originTreeNodes.length; i++) {
                        for (var j = 0; j < destTreeNodes.length; j++) {
                            treeList.push({
                                pyfPyCode: scope.selectPyCode, //策略code
                                pyfFromCode: originTreeNodes[i].code,  //起始地code
                                pyfFromName: originTreeNodes[i].name,  //起始地name
                                pyfToCode: destTreeNodes[j].code,  //目的地code
                                pyfToName: destTreeNodes[j].name   //目的地name
                            })
                        }
                    }
                    scope.areaSelectList = treeList;
                    scope.Tools.initCheckBox();
                }
            }

            //获取选中列表中的数据移除掉
            scope.leftClick = function () {
                var indexArr = scope.Tools.getTableSelectItemIndex('.flowtoTable');  //获取table所选的下标

                var areaSelectList = scope.Tools.getDataTOIndex(indexArr, scope.areaSelectList);

                if (indexArr.length == 0) {
                    return;
                }

                for (var i = 0; i < areaSelectList.length; i++) {
                    for (var j = 0; j < scope.areaSelectList.length; j++) {
                        if (areaSelectList[i].pyfFromCode == scope.areaSelectList[j].pyfFromCode && areaSelectList[i].pyfToCode == scope.areaSelectList[j].pyfToCode) {
                            scope.areaSelectList.splice(j, 1);
                            break;
                        }
                    }
                }
            }

            //保存流向
            scope.saveFlowtoClick = function () {
                stockUnitStrategyService.addPloyFlowto(scope.areaSelectList)
                    .then(function (result) {
                        if (result.success) {
                            scope.ployFlowtoList(scope.selectPyCode);
                            scope.closeThisDialog();
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })
            }
        }
    }])
    .controller('shipmentPlanCtrl', ['$scope', 'shipmentPlanService', 'dropDownService', function (scope, shipmentPlanService, dropDownService) {   //发运计划 ctrl

        //更多条件默认值
        scope.moreText = scope.constant.moreText.spread;
        //更多条件
        scope.moreClick = function () {
            scope.otherForm = !scope.otherForm;
            if (scope.otherForm) {
                scope.moreText = scope.constant.moreText.packUp;
            } else {
                scope.moreText = scope.constant.moreText.spread;
            }
        }

        /*状态数据*/
        scope.dropDownList = {
            shipmentPlanStatus: scope.Tools.dropDown.shipmentPlanStatusDropDown.concat()    //发运计划状态
        }
        scope.dropDownList.shipmentPlanStatus.unshift(scope.constant.defaultDropDownNullData);  //向前插入空值

        //设置默认值
        scope.dropDownDefault = {
            shipmentPlanStatus: scope.dropDownList.shipmentPlanStatus[0] //发运计划状态默认值
        }

        //列表查询接口参数构造
        scope.listParam = function () {

            if (!scope.search) {
                scope.search = {};
            }
            scope.search.pageSize = scope.pageSize;    //设置最大页
            if (!scope.fristSelect) { //不是第一次查询 则设置当前页
                scope.search.pageNo = scope.pageNo;
            } else {  //第一次查询设置为　第一页
                scope.search.pageNo = scope.constant.pageNo;
            }

            if (scope.otherForm) {    //展开了更多
                scope.search.spCustomerName = scope.dropDownDefault.shipper ? scope.dropDownDefault.shipper.wnhCustomerName : '';   //货主
                scope.search.spSendBusinessFlag = scope.dropDownDefault.shipmentPlanStatus.value;   //状态
                return scope.search;
            } else {  //没有展开
                return scope.search;
            }
        }

        //列表
        scope.fristSelect = true;   //判断是否是第一次查询
        scope.list = function (params) {
            //设置分页参数
            if (!params) {
                params = {};
            }
            params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
            params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo;

            shipmentPlanService.getShipmentPLanList(params)
                .then(function (result) {
                    if (result.success) {
                        scope.shipmentPlanList = result.data;
                        scope.outboundOrderDetailList = null;   //置空详情list
                        if (scope.fristSelect) {
                            scope.Tools.page(document.getElementById('page'), {
                                pages: result.pageVo.totalPage,
                                curr: result.pageVo.pageNo,
                                count: result.pageVo.totalRecord
                            }, function (obj, first) {
                                scope.fristSelect = first;  //设置状态
                                //初始化多选框
                                scope.Tools.initCheckBox();
                                if (!first) { //判断不是第一次加载
                                    var param = scope.listParam();
                                    param.pageNo = obj.curr;    //当前页
                                    param.pageSize = obj.limit; //最大页
                                    scope.pageSize = obj.limit; //设置最大页
                                    scope.pageNo = obj.curr; //设置当前页
                                    scope.list(param);
                                }
                            })
                        } else {
                            //初始化多选框
                            scope.Tools.initCheckBox();
                        }
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //列表
        scope.list();

        //回车按下查询
        scope.searchListKeyDown = function (e) {
            var keycode = window.event ? e.keyCode : e.which;
            if (keycode == 13) {  //回车键
                scope.fristSelect = true;   //设置为第一次查询
                scope.list(scope.listParam());
                e.preventDefault();
            }
        }

        //点击每行列表的数据 click
        scope.selectItemClick = function (item, e) {
            scope.Tools.initTableClick(e);  //选中行处理
            if (scope.userInfo.whCode.indexOf(scope.constant.userWarehouseType.UNLCN_XN_) != -1) {    //西南库才起作用
                shipmentPlanService.getShipmentPLanVehicleList(item.spId)
                    .then(function (result) {
                        if (result.success) {
                            scope.outboundOrderDetailList = result.data
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })
            }
        }

        //查询 click
        scope.searchClick = function () {
            scope.fristSelect = true;   //设置为第一次查询
            scope.list(scope.listParam());
        }

        //重置 click
        scope.resetClick = function () {
            scope.search = {};
            scope.dropDownDefault.shipper = scope.dropDownList.shipper[0];  //货主
            scope.dropDownDefault.shipmentPlanStatus = scope.dropDownList.shipmentPlanStatus[0];    //发运状态
        }

        //刷新 click
        scope.refreshClick = function () {
            scope.searchClick();
        }

        //初始化装车道
        var loadLaneArr = new Array();
        for (var i = 1; i <= 4; i++) {
            loadLaneArr.push({name: i, value: i});
        }

        //创建备料计划 click
        scope.createWarehousePlanClick = function () {
            var indexArr = scope.Tools.getTableSelectItemIndex('.shipmentPlanTable');  //获取table所选的下标

            if (indexArr.length == 0) {
                scope.Tools.alert('请选择备料计划数据');
                return;
            }
            var shipmentPlanList = scope.Tools.getDataTOIndex(indexArr, scope.shipmentPlanList);
            scope.Tools.dialog({
                controller: 'shipmentPlanCtrl.dialog',
                template: 'templates/warehouseManagement/shipmentPlan/shipment-plan-form.html',
                closeByDocument: false,
                closeByEscape: false,
                data: {
                    loadLane: loadLaneArr,
                    dropDownDefault: { //默认值
                        loadLane: loadLaneArr[0]
                    },
                    Data: shipmentPlanList
                },
                width: 400,
                title: '创建发运计划',
                scope: scope
            })
        }

        //获取货主
        dropDownService.getCustomerInfo()
            .then(function (result) {
                if (result.success) {
                    scope.dropDownList.shipper = result.data;
                    scope.dropDownList.shipper.unshift(scope.constant.defaultDropDownNullData); //插入空值
                    scope.dropDownDefault.shipper = scope.dropDownList.shipper[0];  //设置默认值
                } else {
                    scope.Tools.alert(result.message);
                }
            })

    }])
    .controller('shipmentPlanCtrl.dialog', ['$scope', 'shipmentPlanService', function (scope, shipmentPlanService) {     //发运计划 ctrl dialog

        scope.flag = true;  //禁止多次点击
        scope.shipment = {
            estimateLoadingTime: '',
            estimateFinishTime: ''
        }
        scope.flagSave = true
        scope.handle = function () {
            scope.Tools.alert('操作正在处理中...');
        }
        //保存发运计划
        scope.saveShipmentPlanClick = function () {
            if (true) {
                scope.flag = false;
                if (!scope.shipment.estimateLoadingTime) {    //判断计划装车时间
                    scope.Tools.alert('请选择计划装车时间');
                    return;
                }

                // if(!scope.shipment || !scope.shipment.estimateFinishTime){    //判断预计完成时间
                //     scope.Tools.alert('请选择预计完成时间');
                //     return;
                // }

                var listArr = new Array();
                angular.forEach(scope.ngDialogData.Data, function (v, k) {
                    listArr.push({
                        spId: v.spId,
                        estimateLoadingTime: scope.shipment.estimateLoadingTime,   //计划装车时间
                        estimateFinishTime: scope.shipment.estimateFinishTime  //预计完成时间
                    });
                });
                scope.flagSave = false
                shipmentPlanService.createPreparationPlan(listArr)
                    .then(function (result) {
                        if (result.success) {
                            scope.Tools.alert('创建发运计划成功');
                            scope.flagSave = true
                            scope.list(scope.listParam());
                            //置空详情list
                            scope.$parent.outboundOrderDetailList = null;
                            scope.closeThisDialog();
                        } else {
                            scope.flagSave = true
                            scope.Tools.alert(result.message);
                        }
                        scope.flag = true;
                    })
            }
        }
    }])
    .controller('shipmentPlanRejectCtrl', ['$scope', '$rootScope', 'dropDownService', 'shipmentPlanRejectService', '$timeout', function (scope, $rootScope, dropDownService, shipmentPlanRejectService, $timeout) {     //发运计划驳回 ctrl
        scope.moreText = scope.constant.moreText.spread;
        //更多条件
        scope.moreClick = function () {
            scope.otherForm = !scope.otherForm;
            if (scope.otherForm) {
                scope.moreText = scope.constant.moreText.packUp;
            } else {
                scope.moreText = scope.constant.moreText.spread;
            }
        }

        /*状态数据*/
        scope.dropDownList = {
            shipmentPlanStatus: scope.Tools.dropDown.shipmentPlanStatusDropDown.concat(),    //发运计划状态
            shipmentPlanType: scope.Tools.dropDown.shipmentPlanTypeDropDown.concat(),   //发运类型
            shipmentRejectStatus: scope.Tools.dropDown.shipmentRejectStatusDropDown.concat() //发运驳回状态
        }
        scope.dropDownList.shipmentPlanStatus.unshift(scope.constant.defaultDropDownNullData);  //向前插入空值
        scope.dropDownList.shipmentPlanType.unshift(scope.constant.defaultDropDownNullData);    //向前插入空值
        scope.dropDownList.shipmentRejectStatus.unshift(scope.constant.defaultDropDownNullData); //发运驳回状态
        //设置默认值
        scope.dropDownDefault = {
            shipmentPlanStatus: scope.dropDownList.shipmentPlanStatus[0], //发运计划状态默认值
            shipmentPlanType: scope.dropDownList.shipmentPlanType[0],   //发运类型状态默认值
            shipmentRejectStatus: scope.dropDownList.shipmentRejectStatus[0]   //发运驳回状态默认值
        }

        //列表查询接口参数构造
        scope.listParam = function () {

            if (!scope.search) {
                scope.search = {};
            }
            scope.search.pageSize = scope.pageSize;    //设置最大页
            if (!scope.fristSelect) { //不是第一次查询 则设置当前页
                scope.search.pageNo = scope.pageNo;
            } else {  //第一次查询设置为　第一页
                scope.search.pageNo = scope.constant.pageNo;
            }

            if (scope.otherForm) {    //展开了更多
                scope.search.spSendBusinessFlag = scope.dropDownDefault.shipmentPlanStatus.value;   //发运计划驳回状态
                scope.search.spDlvType = scope.dropDownDefault.shipmentPlanType.value;  //发运计划类型
                scope.search.spIsReject = scope.dropDownDefault.shipmentRejectStatus.value; //是否有驳回
                return scope.search;
            } else {  //没有展开
                return scope.search;
            }
        }

        $rootScope.reject_listParam = scope.listParam

        scope.search = {
            spOrderNo: '',
            spDeliverWarehouseCode: '',
            spCarrier: '',
            spSendBusinessFlag: '',
            spDlvType: '',
            spIsReject: '',
            startCreateTime: '',
            endCreateTime: '',
            spGroupBoardNo: ''
        };

        //列表
        scope.fristSelect = true;   //判断是否是第一次查询
        scope.shipmentPlanRejectList = null;
        scope.list = function (params) {

            if (!params) {
                params = {};
            }

            params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
            params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo;

            shipmentPlanRejectService.queryShipmentList(params)
                .then(function (result) {
                    if (result.success) {
                        scope.shipmentPlanRejectList = result.data.dataList;
                        scope.queryDetailList = null;   //置空详情list
                        if (scope.fristSelect) {
                            scope.Tools.page(document.getElementById('pageOne'), {
                                pages: result.data.page.totalPage,
                                curr: result.data.page.pageNo,
                                count: result.data.page.totalRecord
                            }, function (obj, first) {
                                scope.fristSelect = first;  //设置状态
                                //初始化多选框
                                scope.Tools.initCheckBox();
                                if (!first) { //判断不是第一次加载
                                    var param = scope.listParam();
                                    param.pageNo = obj.curr;    //当前页
                                    param.pageSize = obj.limit; //最大页
                                    scope.pageSize = obj.limit; //设置最大页
                                    scope.pageNo = obj.curr; //设置当前页
                                    scope.list(param);
                                }
                            })
                        } else {
                            //初始化多选框
                            scope.Tools.initCheckBox();
                        }
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        $rootScope.reject_list = scope.list

        //列表
        scope.list();

        //回车按下查询
        scope.searchListKeyDown = function (e) {
            var keycode = window.event ? e.keyCode : e.which;
            if (keycode == 13) {  //回车键
                scope.fristSelect = true;   //设置为第一次查询
                scope.list(scope.listParam());
                e.preventDefault();
            }
        }

        scope.sprlTrSelect = function (e, eq) {
            scope.Tools.initTableClick(e);  //选中行处理
            $rootScope.currSelectTrTwoEq = eq;
        }

        $rootScope.queryDetailListsprl = [];

        //点击每行列表的数据 click
        scope.selectItemClick = function (e, id) {
            scope.Tools.initTableClick(e);  //选中行处理
            $rootScope.currSelectTr = id;
            shipmentPlanRejectService.queryDetailList(id)
                .then(function (result) {
                    if (result.success) {
                        $rootScope.queryDetailListsprl = result.data
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //查询 click
        scope.searchClick = function () {
            scope.fristSelect = true;   //设置为第一次查询
            scope.list(scope.listParam());
        }

        //重置 click
        scope.resetClick = function () {
            scope.search = {
                spOrderNo: '',
                spDeliverWarehouseCode: '',
                spCarrier: '',
                spSendBusinessFlag: '',
                spDlvType: '',
                spIsReject: '',
                startCreateTime: '',
                endCreateTime: '',
                spGroupBoardNo: ''
            };
            scope.dropDownDefault.shipmentPlanStatus = scope.dropDownList.shipmentPlanStatus[0];   //发运计划状态
            scope.dropDownDefault.shipmentPlanType = scope.dropDownList.shipmentPlanType[0];   //发运计划状态
            scope.dropDownDefault.shipmentRejectStatus = scope.dropDownList.shipmentRejectStatus[0];   //发运计划状态
        }

        //驳回
        scope.shipmentReject = function () {
            var idArr = [];
            var statusArr = []
            $('.sprlTable').find('td i').each(function (index, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('tr').attr('id');
                    var status = $(obj).parents('tr').attr('status1');
                    idArr.push(id);
                    statusArr.push(status)
                }
            });
            if (idArr.length == 1) {
                if (parseInt(statusArr[0]) == 0) {
                    $rootScope.rejectUnDealListId = idArr[0]
                    scope.Tools.dialog({
                        controller: 'rejectUnDealListCtrl.dialog',
                        template: 'templates/warehouseManagement/shipmentPlanReject/reject-undeal-list.html',
                        closeByDocument: false,
                        closeByEscape: false,
                        data: {},
                        width: 1000,
                        title: '未处理订单驳回',
                        scope: scope
                    })

                } else {
                    shipmentPlanRejectService.shipmentReject(idArr[0]).then(function (data) {
                        if (data.success) {
                            scope.Tools.alert(data.message);
                        } else {
                            scope.Tools.alert(data.message);
                        }
                    })
                }


            } else if (idArr.length == 0) {
                scope.Tools.alert('未选择');

            } else if (idArr.length > 1) {
                scope.Tools.alert('驳回只能单选！');
            }
        }

        //刷新 click
        scope.refreshClick = function () {
            scope.searchClick();
        }

        //任务取消 click
        scope.taskCancelClick = function () {
            var idArr = [];
            $('.sprlTableTwo').find('td i').each(function (index, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('tr').attr('id');
                    idArr.push(id);
                }
            });

            if (idArr.length == 1) {
                $rootScope.sprlTaskId = idArr[0];

                scope.Tools.dialog({
                    controller: 'shipmentPlanRejectCtrl.dialog',
                    template: 'templates/warehouseManagement/shipmentPlanReject/task-cancel-form.html',
                    closeByDocument: false,
                    closeByEscape: false,
                    data: {},
                    width: 550,
                    title: '任务取消',
                    scope: scope
                })

            } else if (idArr.length == 0) {
                scope.Tools.alert('未选选择任务！');

            } else if (idArr.length > 1) {
                scope.Tools.alert('取消任务只能单选！');
            }

        };

        //备料更换  click
        scope.outBoundChangeClick = function () {
            var idArr = [];
            $('.sprlTableTwo').find('td i').each(function (index, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('tr').attr('id');
                    idArr.push(id);
                }
            });
            if (idArr.length == 1) {
                $rootScope.sprlTaskId = idArr[0];

                shipmentPlanRejectService.changePrepare({
                    taskId: $rootScope.sprlTaskId,
                    planId: $rootScope.queryDetailListsprl[$rootScope.currSelectTrTwoEq].planId,   //currSelectTrTwoEq
                    planDetailId: $rootScope.queryDetailListsprl[$rootScope.currSelectTrTwoEq].planDetailId
                }).then(function (data) {
                    if (data.success) {
                        $rootScope.sprlDialogTwoOrignialVin = data.data.orignialVin;
                        $rootScope.sprlDialogTwoChangeVin = data.data.changeVin;

                        if (!$rootScope.sprlDialogTwoChangeVin) {    //判断是否是无车可换
                            scope.Tools.alert('无车可换');
                            return;
                        }
                        //刷新列表数据
                        scope.list(scope.listParam());
                        $rootScope.queryDetailListsprl = null;

                        scope.Tools.dialog({
                            controller: 'shipmentPlanRejectCtrl.dialog',
                            template: 'templates/warehouseManagement/shipmentPlanReject/out-bound-change-form.html',
                            closeByDocument: false,
                            closeByEscape: false,
                            data: {},
                            width: 350,
                            title: '备料更换',
                            scope: scope
                        })
                    }
                    scope.Tools.alert(data.message);
                })

            } else if (idArr.length == 0) {
                scope.Tools.alert('未选选择任务！');
            } else if (idArr.length > 1) {
                scope.Tools.alert('备料变更只能单选！');
            }
        }

        // 手动指定换车
        scope.manualChangeClick = function () {
            var idArr = [];
            var statusArr = [];
            var isRejected;
            $('.sprlTableTwo').find('td i').each(function (index, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var parent = $(obj).parents('tr');
                    var id = parent.attr('id');
                    var status = parent.attr('status1');
                    isRejected = parent.attr('isRejected');
                    idArr.push(id);
                    statusArr.push(status)
                }
            });
            if (idArr.length === 1) {
                // if(parseInt(statusArr[0])==50){
                if (isRejected === '10') {
                    $rootScope.sprlTaskId = idArr[0];
                    scope.Tools.dialog({
                        controller: 'manualChangeByVin.dialog',
                        template: 'templates/warehouseManagement/shipmentPlanReject/manual-change-by-vin.html',
                        closeByDocument: false,
                        closeByEscape: false,
                        data: {
                            detail: $rootScope.queryDetailListsprl
                        },
                        width: 350,
                        title: '手工自动换车',
                        scope: scope
                    })
                } else {
                    scope.Tools.alert('未换车数据，才可以换车');
                }

                // } else {
                //     scope.Tools.alert('只有取消状态，才可以换车');
                // }

            } else if (idArr.length === 0) {
                scope.Tools.alert('未选选择任务！');
            } else if (idArr.length > 1) {
                scope.Tools.alert('备料变更只能单选！');
            }
        }
    }])
    .controller('shipmentPlanRejectCtrl.dialog', ['$scope', '$rootScope', 'shipmentPlanRejectService', function (scope, $rootScope, shipmentPlanRejectService) {     //发运计划驳回 ctrl dialog

        //保存任务取消原因 click
        scope.cancleReason = '';
        scope.saveTaskCancelClick = function () {
            if (scope.cancleReason == '') {
                scope.Tools.alert('未填写取消理由！');
            } else {
                var params = {
                    taskId: $rootScope.sprlTaskId,
                    cancleReason: scope.cancleReason
                };
                shipmentPlanRejectService.cancleTask(params)
                    .then(function (data) {
                        if (data.success) {
                            scope.Tools.alert(data.message);
                            scope.closeThisDialog();
                            //    刷新列表
                            shipmentPlanRejectService.queryDetailList($rootScope.currSelectTr)
                                .then(function (result) {
                                    if (result.success) {
                                        $rootScope.queryDetailListsprl = result.data
                                    } else {
                                        scope.Tools.alert(result.message);
                                    }
                                })
                        } else {
                            scope.Tools.alert(data.message);
                        }
                    })
            }
        };

        //备料更换 保存 click
        scope.planDetailId = '';
        scope.planId = '';
    }])
    .controller('manualChangeByVin.dialog', ['$scope', '$rootScope', 'shipmentPlanRejectService', function (scope, $rootScope, shipmentPlanRejectService) {
        scope.manualChangeVin = ''
        scope.saveFlag = false;
        scope.saveManualChangeVin = function () {
            var idArr = [];
            var statusArr = [];
            scope.saveFlag = true;
            $('.sprlTableTwo').find('td i').each(function (index, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('tr').attr('id');
                    var status = $(obj).parents('tr').attr('status1');
                    idArr.push(id);
                    statusArr.push(status);
                }
            });
            // if (parseInt(statusArr[0]) == 50) {
            shipmentPlanRejectService.changeByVin({
                taskId: $rootScope.sprlTaskId,
                planId: $rootScope.queryDetailListsprl[$rootScope.currSelectTrTwoEq].planId,   //currSelectTrTwoEq
                planDetailId: $rootScope.queryDetailListsprl[$rootScope.currSelectTrTwoEq].planDetailId,
                changeVin: scope.manualChangeVin
            }).then(function (data) {
                scope.saveFlag = false;
                if (data.success) {
                    //刷新列表数据
                    scope.list();
                    // 刷新订单下的详情
                    shipmentPlanRejectService.queryDetailList($rootScope.currSelectTr)
                        .then(function (result) {
                            if (result.success) {
                                $rootScope.queryDetailListsprl = result.data
                            } else {
                                scope.Tools.alert(result.message);
                            }
                        })
                    scope.closeThisDialog();
                    setTimeout(function () {
                        scope.Tools.alert(data.message);
                    }, 200)
                } else {
                    scope.Tools.alert(data.message);
                }
            })
            // } else {
            //     scope.Tools.alert('只有取消状态，才可以换车');
            // }
        }
    }])
    .controller('rejectUnDealListCtrl.dialog', ['$scope', '$rootScope', 'shipmentPlanRejectService', function (scope, $rootScope, shipmentPlanRejectService) {
        scope.tableListReject = []
        scope.rejectFlag = false;
        scope.getList = function () {
            shipmentPlanRejectService.rejectUnDealList($rootScope.rejectUnDealListId).then(function (res) {
                if (res.success) {
                    scope.tableListReject = res.data
                    console.log(res)
                } else {
                    scope.Tools.alert(res.message);
                }
            })
        }
        scope.getList()

        //点击每行列表的数据 click
        scope.selectItemClick = function (e) {
            scope.Tools.initTableClick(e);  //选中行处理
        }

        // 驳回确认
        scope.confirmRejectUnDeal = function () {
            scope.rejectFlag = true;
            var idArr = [];
            $('.confirmRejectUnDeal').find('td i').each(function (index, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    var id = $(obj).parents('tr').attr('id');
                    idArr.push(id);
                }
            });
            shipmentPlanRejectService.rejectUnDeal({
                spIds: idArr.toString()
            }).then(function (res) {
                scope.rejectFlag = false;
                if (res.success) {
                    scope.closeThisDialog();
                    // 更新列表
                    $rootScope.reject_list($rootScope.reject_listParam())
                }
                scope.Tools.alert(res.message);
            })
        }
    }])
    .controller('scooterOffRegistrationCtrl', ['$scope', '$rootScope', 'scooterOffRegistrationService', function (scope, rootScope, scooterOffRegistrationService) {     //板车离场登记
        //更多条件默认值
        scope.moreText = scope.constant.moreText.spread;
        //更多条件
        scope.moreClick = function () {
            scope.otherForm = !scope.otherForm;
            if (scope.otherForm) {
                scope.moreText = scope.constant.moreText.packUp;
            } else {
                scope.moreText = scope.constant.moreText.spread;
            }
        };
        scope.search = {
            vehicle: '',
            departureType: '',
            departureInOutType: '',
            startDeparturTime: '',
            endDepartureTime: ''
        };

        scope.openGateList = [
            {name: '自动tms调用成功开启', value: '10'},
            {name: '页面手动开启闸门', value: '20'},
            {name: '系统闸门开启失败', value: '30'}
        ];
        scope.outorInList = [
            {name: '出场', value: 'OUT'},
            {name: '入场', value: 'IN'}
        ];

        // //下拉
        // scope.dropDownList = {
        //     openGateStatus : scope.Tools.dropDown.openGateStatusDropDown.concat(),   //开闸状态
        //     departureType : scope.Tools.dropDown.departureTypeDropDown.concat()  //离场类型
        // };
        // scope.dropDownList.openGateStatus.unshift(scope.constant.defaultDropDownNullData);  //插入开闸状态空值
        // scope.dropDownList.departureType.unshift(scope.constant.defaultDropDownNullData);  //插入离场类型空值
        // //下拉默认值
        // scope.dropDownDefault = {
        //     openGateStatus : scope.dropDownList.openGateStatus[0],   //开闸状态默认值
        //     departureType : scope.dropDownList.departureType[0]  //离场类型
        // };

        //列表查询接口参数构造
        scope.listParam = function () {

            if (!scope.search) {
                scope.search = {};
            }
            scope.search.pageSize = scope.pageSize;    //设置最大页
            if (!scope.fristSelect) { //不是第一次查询 则设置当前页
                scope.search.pageNo = scope.pageNo;
            } else {  //第一次 查询第一页
                scope.search.pageNo = scope.constant.page.pageNo;
            }

            if (scope.otherForm) {    //展开了更多
                // scope.search.drOpenStatus = scope.dropDownDefault.openGateStatus.value; //开闸状态
                // scope.search.drDepartureType = scope.dropDownDefault.departureType.value; //离场类型
                return scope.search;
            } else {  //没有展开
                return {};
            }
        }
        //列表
        scope.fristSelect = true;   //判断是否是第一次查询
        scope.list = function (params) {
            //设置分页参数
            if (!params) {
                params = {};
            }
            params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
            params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo;

            // scope.search.departureType?scope.search.departureType=scope.search.departureType.value:'';
            // scope.search.departureInOutType?scope.search.departureInOutType=scope.search.departureInOutType.value:'';

            //避免出现对象数组引用
            var temp = {
                vehicle: scope.search.vehicle,
                departureType: scope.search.departureType,
                departureInOutType: scope.search.departureInOutType,
                startDeparturTime: scope.search.startDeparturTime,
                endDepartureTime: scope.search.endDepartureTime
            };


            // 判断其是否为对象
            if (scope.search.departureType instanceof Object) {
                temp.departureType = scope.search.departureType.value;
            }
            if (scope.search.departureInOutType instanceof Object) {
                temp.departureInOutType = scope.search.departureInOutType.value;
            }


            params = angular.extend(params, temp);

            console.log(scope.search);

            scooterOffRegistrationService.queryRegisterList(params)
                .then(function (result) {
                    if (result.success) {
                        scope.scooterOffRegistrationList = result.data;

                        if (scope.fristSelect) {
                            scope.Tools.page(document.getElementById('pages'), {
                                pages: result.pageVo.totalPage,
                                curr: result.pageVo.pageNo,
                                count: result.pageVo.totalRecord
                            }, function (obj, first) {
                                scope.fristSelect = first;  //设置状态
                                //初始化多选框
                                // scope.Tools.initCheckBox();
                                if (!first) { //判断不是第一次加载
                                    var param = {};
                                    param.pageNo = obj.curr;    //当前页
                                    param.pageSize = obj.limit; //最大页
                                    scope.pageSize = obj.limit; //设置最大页
                                    scope.pageNo = obj.curr; //设置当前页
                                    scope.list(param);
                                }
                            })
                        } else {
                            //初始化多选框
                            // scope.Tools.initCheckBox();
                        }
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }

        //列表
        rootScope.sorlGetList = scope.list;
        scope.list();


        //查询 click
        scope.searchClick = function () {
            scope.fristSelect = true;   //设置为第一次查询
            scope.list();
        }

        //重置 click
        scope.resetClick = function () {
            scope.search = {
                vehicle: '',
                departureType: '',
                departureInOutType: '',
                startDeparturTime: '',
                endDepartureTime: ''
            };
            scope.list();
        }

        //刷新 click
        scope.refreshClick = function () {
            scope.searchClick();
        }

        //正常离场
        scope.normalDepartureClick = function () {

            var indexArr = scope.Tools.getTableSelectItemIndex('.scooterOffRegistrationTable');  //获取table所选的下标

            var scooterOffRegistrationList = scope.Tools.getDataTOIndex(indexArr, scope.scooterOffRegistrationList);

            if (scooterOffRegistrationList.length == 0) {
                scope.Tools.alert('请选择一条数据');
                return;
            }

            if (scooterOffRegistrationList.length > 1) {
                scope.Tools.alert('只能选择一条数据');
                return;
            }

            if (scooterOffRegistrationList[0].drDepartureType) {
                scope.Tools.alert('请选择一条未操作的数据');
                return;
            }

            scope.Tools.dialog({
                controller: 'scooterOffRegistrationCtrl.dialog',
                template: 'templates/warehouseManagement/scooterOffRegistration/scooter-off-registration-form.html',
                closeByDocument: false,
                closeByEscape: false,
                data: {
                    departureType: scope.constant.departureType.normalDeparture,    //离场类型
                    scooterOffRegistration: {
                        drId: scooterOffRegistrationList[0].drId   //id
                    }
                },
                width: 450,
                title: '正常离场',
                scope: scope
            })
        }

        //异常离场
        scope.errorDepartureClick = function () {

            var indexArr = scope.Tools.getTableSelectItemIndex('.scooterOffRegistrationTable');  //获取table所选的下标

            var scooterOffRegistrationList = scope.Tools.getDataTOIndex(indexArr, scope.scooterOffRegistrationList);

            if (scooterOffRegistrationList.length == 0) {
                scope.Tools.alert('请选择一条数据');
                return;
            }

            if (scooterOffRegistrationList.length > 1) {
                scope.Tools.alert('只能选择一条数据');
                return;
            }

            if (scooterOffRegistrationList[0].drDepartureType) {
                scope.Tools.alert('请选择一条未操作的数据');
                return;
            }

            scope.Tools.dialog({
                controller: 'scooterOffRegistrationCtrl.dialog',
                template: 'templates/warehouseManagement/scooterOffRegistration/scooter-off-registration-form.html',
                closeByDocument: false,
                closeByEscape: false,
                data: {
                    departureType: scope.constant.departureType.errorDeparture,    //离场类型
                    scooterOffRegistration: {
                        drId: scope.scooterOffRegistrationList[0].drId   //id
                    }
                },
                width: 450,
                title: '异常离场',
                scope: scope
            })
        };
        scope.exportSrc = '#';

        scope.formatGet = function (obj) {
            var temp = '?';
            var tempObj = {
                userId: scope.userInfo.id,
                whCode: scope.userInfo.whCode
            };
            var selfObj = angular.extend(obj, tempObj);
            for (var k in selfObj) {
                temp += (k + '=' + selfObj[k]) + '&'
            }
            return temp;
        };

        scope.export = function () {
            // scope.Tools.dialog({
            //     controller : 'scooterOffRegistrationCtrl.dialog',
            //     template : 'templates/warehouseManagement/scooterOffRegistration/layer/export.html',
            //     width : 190,
            //     title : '导出'
            // })

            //避免出现对象数组引用
            var temp = {
                vehicle: scope.search.vehicle,
                departureType: scope.search.departureType,
                departureInOutType: scope.search.departureInOutType,
                startDeparturTime: scope.search.startDeparturTime,
                endDepartureTime: scope.search.endDepartureTime
            };

            // 判断其是否为对象
            if (scope.search.departureType instanceof Object) {
                temp.departureType = scope.search.departureType.value;
            }
            if (scope.search.departureInOutType instanceof Object) {
                temp.departureInOutType = scope.search.departureInOutType.value;
            }

            // console.log(scope.search);

            scope.exportSrc = contextPath + 'gate/gateRecordsImpot' + scope.formatGet(scope.search);
        };
        //enter  出场-- 开启
        scope.openGate = function (str, type) {
            scope.Tools.dialog({
                controller: 'scooterOffRegistrationCtrl.dialog',
                template: 'templates/warehouseManagement/scooterOffRegistration/layer/openGate.html',
                width: 190,
                data: {
                    drId: str,
                    type: type
                },
                title: '异常原因'
            })
        };
    }])
    .controller('scooterOffRegistrationCtrl.dialog', ['$scope', '$rootScope', 'ngDialog', 'scooterOffRegistrationService', 'gateService', function (scope, rootScope, ngDialog, scooterOffRegistrationService, gateService) {     //板车离场登记 dialog

        // 出场离场判断
        scope.departureInOutFlag = scope.ngDialogData.type || '';

        //保存离场原因 click
        scope.saveDepartureReasonClick = function () {
            if (scope.ngDialogData.departureType == scope.constant.departureType.normalDeparture) {   //正常离场
                scooterOffRegistrationService.normarDeparture(scope.ngDialogData.scooterOffRegistration)
                    .then(function (result) {
                        if (result.success) {
                            scope.Tools.alert('登记成功');
                            scope.list(scope.listParam());
                            scope.closeThisDialog();
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })
            } else if (scope.ngDialogData.departureType == scope.constant.departureType.errorDeparture) {  //异常离场
                scooterOffRegistrationService.errorDeparture(scope.ngDialogData.scooterOffRegistration)
                    .then(function (result) {
                        if (result.success) {
                            scope.Tools.alert('登记成功');
                            scope.list(scope.listParam());
                            scope.closeThisDialog();
                        } else {
                            scope.Tools.alert(result.message);
                        }
                    })
            }
        };
        // 出库确认，并开启闸门
        scope.confirmEnter = function () {
            // 调取后台
            var params = {
                drId: scope.ngDialogData.drId,
                departureReason: scope.reason
            };
            scooterOffRegistrationService.outboundGateOpen(params).then(function (res) {
                if (res.success) {
                    //入库类型查询 并打开闸门
                    var params = {
                        gateType: 20,
                        inOutType: scope.ngDialogData.type
                    };
                    gateService.getByType(params)
                        .then(function (result) {
                            if (result.success) {
                                gateService.open(result.data.channel, scope.constant.gateController.open, '出场成功，闸门已打开', '出场成功，闸门已打开', '出场成功，闸门已打开')
                                    .success(function (data, status, headers, config) {
                                        scope.Tools.alert('闸门打开成功');
                                    })
                                    .error(function (data, status, headers, config) {
                                        scope.Tools.alert('闸门打开失败');
                                    })
                            } else {
                                scope.Tools.alert(result.message);
                            }
                        });
                    // 成功
                    scope.closeThisDialog();
                    rootScope.sorlGetList();
                    setTimeout(function () {
                        scope.Tools.alert(res.message);
                    }, 100);
                } else {
                    // 失败
                    scope.closeThisDialog();
                    scope.Tools.alert(res.message);
                }
            });
            console.log('drId', scope.ngDialogData.drId)
        };


        //    导出
        scope.reason = '';
        scope.enterFlag = false;
        scope.dgChange = function () {
            if (scope.reason) {
                scope.enterFlag = true;
            } else {
                scope.enterFlag = false;
            }
        }
    }])
    .controller('searchWaybillStatusCtrl', ['$scope', '$rootScope', '$timeout', 'searchWaybillStatusService', function ($scope, $rootScope, $timeout, searchWaybillStatusService) {

        $scope.moreClick = function () {                  //    显示更多条件
            $('.otherForm').slideToggle(500);
        };
        // $scope.excelUrl = 'http://10.2.4.76:8090/wms-extra-web/vehicleTracking/importOutExcel?&pageNo=1&pageSize=10&orderno=0171344810&vin=&orderBegin=&orderEnd=&inboundBegin=&inboundEnd=&whCode=UNLCN_XN_CQ&userId=16';


        $scope.tableList = [];

        //    显示更多条件
        $scope.moreClick = function () {
            $('.otherForm').slideToggle(500);
        };

        //搜索对象
        $scope.search = {
            orderno: '',
            vin: '',
            orderBegin: '',
            orderEnd: '',
            inboundBegin: '',
            inboundEnd: '',
            whCode: $scope.userInfo.whCode,
            userId: $scope.userInfo.id
        };
        $scope.isNull = function (obj) {
            for (var k in obj) {
                if (obj[k]) {
                    return true;
                }
            }
            return false;
        };
        $scope.fristSelect = true;

        $scope.formatData = function (obj) {
            var str = '?';
            for (var k in obj) {
                str += '&' + k + '=' + obj[k];
            }
            return str;
        };
        $scope.excelUrl = '#';
        $scope.getData = function (e) {
            if ($scope.tableList.length > 0) {
                $scope.excelUrl = contextPath + '/vehicleTracking/importOutExcel' + $scope.formatData($scope.search);
            } else {
                e.preventDefault();
                $scope.Tools.alert('没有数据，不能导出表格！');
            }

        };

        //导出表格
        $scope.importOutExcel = function () {
            var params = {
                pageNo: $scope.pageNo || 1,
                pageSize: $scope.pageSize || 10
            };
            params = $scope.formatData(angular.extend(params, $scope.search));
            searchWaybillStatusService.importOutExcel(params).then(function (res) {

            })
        };

        //    获取列表
        $scope.getList = function () {
            var params = {
                pageNo: $scope.pageNo || 1,
                pageSize: $scope.pageSize || 10,
            };
            params = angular.extend(params, $scope.search);
            var index = layer.load(2);
            searchWaybillStatusService.getTrackList(params)
                .then(function (result) {
                    if (result.success) {
                        layer.close(index);
                        $scope.tableList = result.data;
                        if ($scope.fristSelect) {
                            $scope.Tools.page(document.getElementById('pages'), {
                                pages: result.pageVo.totalPage,
                                curr: result.pageVo.pageNo,
                                count: result.pageVo.totalRecord
                            }, function (obj, first) {
                                $scope.fristSelect = first;  //设置状态

                                if (!first) { //判断不是第一次加载
                                    var param = {};
                                    param.pageNo = obj.curr;    //当前页
                                    param.pageSize = obj.limit; //最大页
                                    $scope.pageSize = obj.limit; //设置最大页
                                    $scope.pageNo = obj.curr; //设置当前页
                                    $scope.getList(param);
                                }
                            })
                        }
                    } else {
                        layer.close(index);
                        $scope.Tools.open(result.message);
                        $scope.tableList = [];
                    }
                })
        };

        //刷新
        $scope.refreshClick = function () {
            $scope.getList()
        };

        $scope.searchClick = function () {
            if ($scope.isNull($scope.search)) {
                if ($scope.Tools.isRange($scope.search.orderBegin, $scope.search.orderEnd)) {
                    if ($scope.Tools.isRange($scope.search.inboundBegin, $scope.search.inboundEnd)) {
                        $scope.getList();
                    } else {
                        $scope.Tools.alert('入库起始时间必须小于等于入库结束时间！');
                    }
                } else {
                    $scope.Tools.alert('下单起始时间必须小于等于下单结束时间！');
                }

            } else {
                $scope.Tools.alert('至少输入一个查询条件');
            }
        };
        $scope.resetClick = function () {
            $scope.search = {
                orderno: '',
                vin: '',
                orderBegin: '',
                orderEnd: '',
                inboundBegin: '',
                inboundEnd: '',
                whCode: $scope.userInfo.whCode,
                userId: $scope.userInfo.id
            };
        };
    }]);